load('application');

before(loadTest, {only: ['show', 'edit', 'update', 'destroy']});

action('new', function () {
    this.title = 'New test';
    this.test = new Test;
    render();
});

action(function create() {
    Test.create(req.body.Test, function (err, test) {
        if (err) {
            flash('error', 'Test can not be created');
            render('new', {
                test: test,
                title: 'New test'
            });
        } else {
            flash('info', 'Test created');
            redirect(path_to.tests());
        }
    });
});

action(function index() {
    this.title = 'Tests index';
    Test.all(function (err, tests) {
        render({
            tests: tests
        });
    });
});

action(function show() {
    this.title = 'Test show';
    render();
});

action(function edit() {
    this.title = 'Test edit';
    render();
});

action(function update() {
    this.test.updateAttributes(body.Test, function (err) {
        if (!err) {
            flash('info', 'Test updated');
            redirect(path_to.test(this.test));
        } else {
            flash('error', 'Test can not be updated');
            this.title = 'Edit test details';
            render('edit');
        }
    }.bind(this));
});

action(function destroy() {
    this.test.destroy(function (error) {
        if (error) {
            flash('error', 'Can not destroy test');
        } else {
            flash('info', 'Test successfully removed');
        }
        send("'" + path_to.tests() + "'");
    });
});

function loadTest() {
    Test.find(params.id, function (err, test) {
        if (err || !test) {
            redirect(path_to.tests());
        } else {
            this.test = test;
            next();
        }
    }.bind(this));
}
